package zondy.yapi.extProject.messageListener;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.changestream.ChangeStreamDocument;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.messaging.Message;
import org.springframework.data.mongodb.core.messaging.MessageListener;
import org.springframework.stereotype.Component;
import zondy.yapi.extProject.send.DingTalkMessageSend;
import zondy.yapi.extProject.util.TextUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 文档消息监听
 *
 * @author 管子
 * @date 2024/7/31 22:10
 * @description: DocumentMessageListener 类
 */
@Slf4j
@Component
public class DocumentMessageListener implements MessageListener<ChangeStreamDocument<Document>, Document> {

    @Autowired
    private MongoTemplate mongoTemplate;

    private static Map<String, String> projectMap = new ConcurrentHashMap<>();

    @Override
    public void onMessage(Message<ChangeStreamDocument<Document>, Document> message) {
        log.info("监听到yapi动态: {}", message.getBody());

        Document document = message.getBody();
        if (document == null) {
            return;
        }
        String content = document.getString("content");
        Integer typeid = document.getInteger("typeid");

        String projectName = getProjectName(String.valueOf(typeid));

        while (content.contains("<")) {
            content = TextUtils.clearBracket(content, '<', '>');
        }

        if (StringUtils.isBlank(projectName)) {
            projectName = "";
        } else {
            projectName = projectName + "项目中 ";
        }
        content = projectName + content;
        log.info("content: {}", content);

        try {
            new DingTalkMessageSend().sendMessage(null, content);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据项目id获取项目名称
     *
     * @param typeid 项目id
     * @return
     */
    private String getProjectName(String typeid) {
        String projectName = projectMap.get(typeid);
        if (StringUtils.isNotEmpty(projectName)) {
            return projectName;
        } else {
            MongoCollection<Document> project = mongoTemplate.getCollection("project");
            FindIterable<Document> projectDocuments = project.find();
            projectMap.clear();
            for (Document projectDocument : projectDocuments) {
                System.out.println(projectDocument);
                String name = (String) projectDocument.get("name");
                String id = String.valueOf(projectDocument.get("_id"));
                projectDocument.put(id, name);
            }
            return projectName;
        }

    }
}
